<?php


namespace FoxLib\Services;


use FoxLib\Exceptions\FileUploadException;
use OSS\Core\OssException;
use OSS\OssClient;

class OssService
{
    public static function upload($filePath, $fileExt)
    {
        try {
            $ossId = config('aliyun.access_key_id');
            $ossSecret = config('aliyun.access_key_secret');
            $ossEndpoint = config('aliyun.oss_endpoint');
            $ossBucket = config('aliyun.oss_bucket');
            $ossPathPrefix = config('aliyun.oss_path_prefix');

            $ossClient = new OssClient($ossId, $ossSecret, $ossEndpoint);
            $ossClient->setUseSSL(true);
            if (!$ossClient->doesBucketExist($ossBucket)) {
                $ossClient->createBucket($ossBucket);
            }
            $hashName = md5(uniqid(rand(), true));
            $saveFilename =  $ossPathPrefix . '/' . substr($hashName, 0, 2) . '/' . substr($hashName, -2) . '/' .  $hashName.  '.' . $fileExt;
            $result = $ossClient->uploadFile($ossBucket, $saveFilename, $filePath);
            return $result['oss-request-url'];
        } catch (OssException $e) {
            throw new FileUploadException();
        }
    }
}